
const Thing = require('../models/Thing');



/**
 * GET /creatething
 * creatething page.
 */
exports.getCreateThing = (req, res) => {
  res.render('thing/create', {
    title: 'create a thing'
  });
};

/**
 * POST /creatething
 * creatething page.
 */
 exports.postCreateThing = (req, res) => {
  const thing = new Thing({
    title: req.body.title,
    body: req.body.body,
    url:req.body.url
  });
  thing.save((err,saved_thing) => {
    if (err) { 
      req.flash('errors', { msg: '创建失败' });
      return next(err); 
    }
    
    console.log(saved_thing);
    req.flash('success', { msg: 'Success Created a thing.' });
    res.render('thing/createsuccess', {
      title: 'create a thing',
      thing: saved_thing
    });
  });

};


/**
 * GET /readthing
 * read a thing page.
 */
 exports.getReadThing = (req, res) => {
  //console.log(req.params);
  Thing.findById(req.params.thingid, (err, found_thing) => {
   // if (err) { return next(err); }
      //console.log(found_thing);
      res.render('thing/read', {
        title: 'read a thing',
        thing: found_thing
      });
  });
};


/**
 * POST /updatething
 * update a thing.
 */
 exports.getUpdateThing = (req, res) => {

    //console.log(req.params);
    Thing.findById(req.params.thingid, (err, found_thing) => {
      if (err) { return next(err); }
        //console.log(found_thing);
        res.render('thing/update', {
          title: 'read a thing',
          thing: found_thing
        });
    });
  
};

/**
 * POST /updatething
 * update a thing.
 */
 exports.postUpdateThing = (req, res) => {
  Thing.findById(req.params.thingid, (err, thing_to_update) => {
    if (err) { return next(err); }
    thing_to_update.body = req.body.body;
    thing_to_update.url = req.body.url;

    thing_to_update.save((err,saved_thing) => {
      if (err) { return next(err); }
      req.flash('success', { msg: '更新成功 has been changed.' });
      res.redirect('/thing/read/'+saved_thing._id);
    });
  });

};




/**
 * POST /things
 * list a thing page.
 */
 exports.getListThing = (req, res) => {
  Thing.find(function (err, finded_things) {
    console.log(finded_things);
    res.render('thing/list', {
      title: 'list  things',
      things: finded_things
    });
  });

};


/**
 * GET /thing/delete/:thingid
 * 
 */
 exports.getDeleteThing = (req, res) => {
  Thing.findOneAndDelete({ _id: req.params.thingid },function (err){
    if (err) { return next(err); }
    req.flash('success', { msg: '删除成功 ' });
    res.redirect('/things');
  })

};

/**
 * GET /cratething
 * cratething page.
 */
 exports.getCreateThing = (req, res) => {
  res.render('thing/create', {
    title: 'create a thing'
  });
};
